<template>
  <div>
    <Form :label-width="150" ref="formInline" :model="formInline">
      <Row :gutter="16" class="query-form">
        <i-col span="8">
          <FormItem label="审计标准名称(裁剪后)：">
            <Input v-model="formInline.auditName"/>
          </FormItem>
        </i-col>

        <i-col span="8" :offset="8">
          <Button class="ivu-btn-reset" @click="cancel">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </i-col>
      </Row>
    </Form>
    <Row type="flex" justify="start" class="query-form">
      <i-col>
        <Button icon="md-add" class="ivu-btn-add" :loading="addloading" @click="addInfo">新增</Button>
        <Button size="large" class="ivu-btn-add" icon="md-home" @click="back">返回</Button>
      </i-col>
    </Row>
    <Table ref='table' style="margin-top: 10px" :loading="loading" border :columns="columns"
           :data="infos" width="100%" :height="tableHeight" highlight-row stripe size="small"></Table>
    <Row type="flex" justify="end">
      <i-col>
        <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"
              @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray" show-total
              show-sizer show-elevator/>
      </i-col>
    </Row>

    <Modal :title="modalTitle" :transfer=false v-model="model1" :closable="false" :mask-closable="false" :width="900"
           :styles="{top: '20px'}">
      <Form ref="formCustom" :model="formData" :rules="ruleCustom" label-position="top">
        <Row :gutter="16">
          <i-col span="12">
            <FormItem label="被审计单位：" prop="companyId">
              <!--              <Input v-model="formData.companyName" :readonly="true"/>-->
              <!--
                            <cascaderDom ref="trainOrg" @setOrgInfo="setOrgId" @setOrgname="setOrgName" style="width: 100%;"
                                         :currentOrgId="formData.companyId" :currentOrgName="formData.companyName" :orgTree="true" rootOrgId="18000000"></cascaderDom>
              -->

              <Select v-model="formData.companyId" placeholder="请先选择审计计划" filterable @on-change="setAuditOrg"
                      label-in-value style="width: 100%">
                <Option v-for="orgInfo in orgList" :key="orgInfo.orgId" :value="orgInfo.orgId">{{ orgInfo.orgName }}
                </Option>
              </Select>
            </FormItem>
          </i-col>
          <i-col span="12">
            <FormItem label="审计标准名称(裁剪后)：" prop="auditName">
              <Input v-model="formData.auditName" readonly/>
            </FormItem>
          </i-col>

        </Row>
        <Row :gutter="16">
          <i-col span="12">
            <FormItem label="审计计划：" prop="auditPlanId">
              <Select v-model="formData.auditPlanId" style="width:100%" @on-change="changePlanJinyu">
                <Option v-for="item in auditPlanList" :value="item.auditPlanId">{{ item.auditPlanName }}</Option>
              </Select>
            </FormItem>
          </i-col>
          <i-col span="12">

          </i-col>

        </Row>
        <Row :gutter="16">
          <i-col span="12">
            <FormItem label="审计类型：" prop="auditType">
              <Select v-model="formData.auditType" style="width:100%" @on-change="auditStandards" label-in-value>
                <Option value="1">基础标准</Option>
                <Option value="2">现场标准</Option>
                <Option value="3">班组标准</Option>
              </Select>
            </FormItem>
          </i-col>
          <i-col span="12">
            <FormItem label="审计标准：" prop="standardsId">
              <Select v-model="formData.standardsId" style="width:100%" @on-change="auditTree">
                <Option v-for="item in standards" :value="item.id">{{ item.auditName }}</Option>
              </Select>
            </FormItem>
          </i-col>
        </Row>
      </Form>
      <div style="height: 400px; overflow-y: auto; overflow-x: auto;">
        <Tree ref="auditTree" show-checkbox multiple :data="orderTreeHead"></Tree>
      </div>
      <div slot="footer">
        <Button type="primary" class='ivu-btn-save' @click="saveInfo" :loading="buttonLoading">确定</Button>
        <Button type="primary" class='ivu-btn-cancel' @click="model1=false" :loading="buttonLoading">取消</Button>
      </div>
    </Modal>
    <Modal title="企业涉及安全标准裁剪详情" :transfer=false v-model="model2" :closable="false" :mask-closable="false" :width="900"
           :styles="{top: '20px'}">
      <Form :label-width="160">
        <Row :gutter="16">
          <i-col span="12">
            <FormItem label="被审计单位：">
              {{ formData.companyName }}
            </FormItem>
          </i-col>
          <i-col span="12">
            <FormItem label="审计标准名称(裁剪后)：">
              {{ formData.auditName }}
            </FormItem>
          </i-col>

        </Row>
        <Row :gutter="16">
          <i-col span="12">
            <FormItem label="审计类型：">
              {{ formData.auditType === '1' ? '基础标准' : formData.auditType === '2' ? '现场标准' : '班组标准' }}
            </FormItem>
          </i-col>
          <i-col span="12">
            <FormItem label="审计标准：">
              {{ formData.standardsName }}
            </FormItem>
          </i-col>
        </Row>

      </Form>
      <div style="height: 400px; overflow-y: auto; overflow-x: auto;">
        <Tree show-checkbox multiple :data="orderTreeHead"></Tree>
      </div>
      <div slot="footer">
        <Button class="ivu-btn-cancel" @click="model2=false">关闭</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {sessionStorage} from '@/common/cacheUtils.js';
import {Api} from '../../../api'

var cascaderDom = () => import('@/components/cascader-dom.vue');

export default {
  name: "AuditTailoring",
  components: {cascaderDom},
  data() {
    return {
      crrentUser: sessionStorage('userId').getObject('userId'),
      buttonLoading: false,
      addloading: false,
      rootOrgId: '',
      planList: [],
      standards3: [],
      isHead: true,
      ztreeObj: null,
      lastPostName: "",
      modalTitle: "",
      setCurrentScreenPositionName: {},
      loginId: "",
      currentUserId: "",
      positions: [],
      auditPlanList: [],
      isUpdate: false,
      model1: false,
      model2: false,
      loading: false,
      isRole: false,
      isPost: false,
      isPro: false,
      isProType: false,
      formInline: {postId: "", name: ""},
      copyData: {},
      orgList: [],
      columns: [
        {
          type: 'index',
          title: '序号',
          width: 80,
          fixed: 'left',
          align: 'center',
          render: (h, params) => {
            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
          }
        },
        {
          title: '被审计单位',
          align: 'center',
          key: 'companyName',
          minWidth: 200,
          render: (h, params) => {
            return h('div', [
              h('span', params.row.companyName || '--')
            ]);
          }
        },
        {
          title: '审计标准名称(裁剪后)',
          align: 'center',
          key: 'auditName',
          minWidth: 140,
          render: (h, params) => {
            return h('div', [
              h('span', params.row.auditName || '--')
            ]);
          }
        },
        {
          title: '审计计划',
          align: 'center',
          key: 'auditPlanName',
          minWidth: 200,
        },
        {
          title: '审计标准',
          align: 'center',
          key: 'auditType',
          minWidth: 90,
          render: (h, params) => {
            return h('div', [
              h('span', params.row.auditType === '1' ? '基础标准' : params.row.auditType === '2' ? '现场标准' : '班组标准')
            ]);
          }
        },
        {
          title: '上报人',
          align: 'center',
          key: 'userName',
          minWidth: 140,

        },
        {
          title: '上报时间',
          align: 'center',
          key: 'postName',
          minWidth: 140,
          render: (h, params) => {
            return h('div', [
              h('span', this.formatDate(new Date(params.row.createDate), 'yyyy-MM-dd'))
            ]);
          }

        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          minWidth: 160,
          fixed: 'right',
          render: (h, params) => {
            if (this.crrentUser.loginId === this.Common.admin || this.crrentUser.userId === params.row.createUserId || this.crrentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined) {
              return h('div', [
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px',
                  },
                  on: {
                    click: () => {
                      this.showData(params, 1);
                    }
                  }
                }, '详情'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px',

                  },
                  on: {
                    click: () => {
                      this.showData(params, 2);
                    }
                  }
                }, '修改'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px',
                    color: 'red'
                  },
                  on: {
                    click: () => {
                      this.$Modal.confirm({
                        title: '提示',
                        content: '<p>是否要删除？</p>',
                        onOk: () => {
                          this.deleteData(params);
                        },
                        onCancel: () => {
                        }
                      });
                    }
                  }
                }, '删除')
              ]);
            } else {
              return h('div', [
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px',},
                  on: {
                    click: () => {
                      this.showData(params, 1);
                    }
                  }
                }, '详情'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce'}
                }, '修改'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce'}
                }, '删除')
              ]);
            }

          }
        },
      ],
      infos: [],
      planDict: null,
      tableHeight: 0,
      standards: [],
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1
      },
      pageSizeArray: [10, 20, 50],
      ruleCustom: {
        companyId: [
          {
            required: true,
            message: '  ',
            trigger: 'change'
          }
        ],
        auditPlanId: [
          {
            required: true,
            message: '  ',
            trigger: 'change'
          }
        ],
        auditName: [
          {
            required: true,
            message: '  ',
            trigger: 'change'
          }
        ],
        auditType: [
          {
            required: true,
            message: '  ',
            trigger: 'change'
          }
        ],
        standardsId: [
          {
            required: true,
            message: '  ',
            trigger: 'change'
          }
        ],

      },
      formData: {},
      orderTree: [
        {
          id: 1,
          name: '隐患条目',
          open: true,
          pid: 0
        }
      ],
      orderTreeHead: [
        {
          id: 1,
          loading: false,
          title: '隐患条目',
          expand: false,
          children: []
        }
      ],
      setingTree: {
        check: {
          enable: true
        },
        data: {
          simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "parent_id",
          },
          key: {
            children: "childList"
          },
        },
        view: {
          showIcon: false,
          showLine: true,
        }
      },
      standards2: [],
      standards1: [],

    }
  },
  mounted() {
    this.getPlanAll();
    this.currentUserId = sessionStorage('userId').getObject('userId').userId;
    this.loginId = sessionStorage('userId').getObject('userId').loginId;
    let user = sessionStorage('userId').getObject('userId');
    this.rootOrgId = user.companyId;
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
    this.addloading = true;
    this.$http.get(Api.getAuditTwoPlan).then(function (res) {
      this.addloading = false;
      this.auditPlanList = res.data.data;
      this.planDict = {};
      this.auditPlanList.forEach(item => {
        this.planDict[item.auditPlanId] = item;
      })
    }, function (res) {
      this.$Message.error('请求失败');
    });
    this.query();
    this.audit();
  },
  methods: {
    getPlanAll() {
      let _this = this;
      this.$http.get(Api.getPlanTwoAll).then((res) => {

        _this.planList = res.data.data.list
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    auditTree(item) {
      let _this = this;
      _this.orderTreeHead = [{
        id: 1,
        loading: true,
        title: '安全审计标准',
        expand: false,
        children: [],
      }]
      if (this.formData.standardsId) {
        this.buttonLoading = true;
        this.$http.get(Api.queryAuditTwoStandardsTreeList, {
          params: {standardId: item}
        }).then(function (res) {
          if (res.data.status == '200') {

            _this.orderTreeHead =
                [
                  {
                    id: 1,
                    loading: false,
                    title: '安全审计标准',
                    expand: true,
                    children: res.data.data
                  }
                ]
          }
          this.buttonLoading = false;
        }, function (res) {
          this.$Message.error('请求失败');
        });
      } else {
        _this.orderTreeHead = [{
          id: 1,
          loading: false,
          title: '安全审计标准',
          expand: false,
          children: [],
        }]
      }

    },
    back() {
      this.$router.push({path: 'AuditTwoTailoring'})
    },
    setAuditOrg(data) {
      this.formData.companyId = data.value;
      this.formData.companyName = data.label;
      if (this.formData.companyName) {
        this.formData.auditName = this.formData.companyName + "_" + this.formData.auditTypeName
      }

    },
    deleteData(params) {
      let url = Api.deleteAuditTwoStandardsTreeList;
      this.$http.delete(url + '/' + params.row.id + "/" + params.row.auditType, {params: {}}).then((res) => {
        if (res.data.status === 200) {
          this.$Message.success('成功');
          this.query()
        } else if (res.data.status === 201) {
          this.$Message.error(res.data.msg);

        } else if (res.data.status === 202) {
          this.$Message.warning(res.data.msg);
        }
      }).catch(e => {
        this.$Message.error('请求失败' + e);
      })
    },
    audit() {
      let _this = this;
      this.$http.get(Api.getStandads, {
        params: {}
      }).then(function (res) {
        if (res.data.status == '200') {
          _this.standards1 = res.data.data.data1;
          _this.standards2 = res.data.data.data2;
          _this.standards3 = res.data.data.data3;
        }
      }, function (res) {
        this.$Message.error('请求失败');
      });

    },
    /*handleSpan({row, column, rowIndex, columnIndex}) {
      if (columnIndex === 1 ) {
        return {
          rowspan: row.mergeCol === 0 ? 0:row.mergeCol,
          colspan: row.mergeCol === 0 ? 0:1
        };
      }
    },*/
    integratedData(data) {
      let that = this;
      // 获取所有的不同年龄值
      let arrId = [];
      data.forEach(i => {
        let createDate = this.formatDate(new Date(i.createDate), 'yyyy');
        console.log(createDate)
        !arrId.includes(createDate + i.companyName) ? arrId.push(createDate + i.companyName) : arrId;
      });
      // 提前为每个年龄值设置跨行数为0
      let arrObj = [];
      arrId.forEach(j => {
        arrObj.push({
          id: j,
          num: 0
        })
      })
      // 计算每个年龄的可跨行数
      data.forEach(k => {
        arrObj.forEach(l => {
          this.formatDate(new Date(k.createDate), 'yyyy') + k.companyName === l.id ? l.num++ : l.num;
        })
      })
      data.forEach(m => {
        arrObj.forEach((n, index) => {
          if (this.formatDate(new Date(m.createDate), 'yyyy') + m.companyName === n.id) {
            if (arrId.includes(this.formatDate(new Date(m.createDate), 'yyyy') + m.companyName)) {
              m.mergeCol = n.num;
              arrId.splice(arrId.indexOf(this.formatDate(new Date(m.createDate), 'yyyy') + m.companyName), 1);
            } else {
              m.mergeCol = 0;
            }
          }
        })
      })
      return data;
    },
    auditStandards(standards) {
      this.$set(this.formData, 'standardsId', null);
      this.standards = [];
      if (standards.value === '1') {
        this.standards = this.standards1
      } else if (standards.value === '2') {
        this.standards = this.standards2
      } else {
        this.standards = this.standards3
      }
      this.formData.auditTypeName = standards.label;
      this.formData.auditName = this.formData.companyName + "_" + this.formData.auditTypeName;


    },
    query() {
      this.loading = true;
      let user = sessionStorage('userId').getObject('userId');
      this.formInline.companyId = this.$route.query.companyId
      this.formInline.auditPlanId = this.$route.query.auditPlanId
      let data = {
        startPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize,
        conditions: this.formInline
      };
      this.$http.post(Api.listTwoAuditTailDetail, data).then(function (res) {
        this.infos = this.integratedData(res.data.data.data);
        this.pagedata.total = res.data.data.totalSize;
        this.loading = false;
      }, function (res) {
        this.$Message.error('请求失败');
      });
    },
    showData(params, type) {
      this.formData = JSON.parse(JSON.stringify(params.row));
      if (type === 1) {
        //详情
        let _this = this;
        _this.orderTreeHead = [{
          id: 1,
          loading: true,
          title: '安全审计标准',
          expand: false,
          children: [],
        }]
        this.model2 = true;
        this.$http.get(Api.checkerAuditTwoStandardsTreeList, {
          params: {standardsId: params.row.standardsId, id: params.row.id}
        }).then(function (res) {
          if (res.data.status == '200') {
            _this.orderTreeHead =
                [
                  {
                    id: 1,
                    loading: false,
                    title: '安全审计标准',
                    expand: true,
                    children: res.data.data
                  }
                ]
          }
        }, function (res) {
          this.$Message.error('请求失败');
        });
      } else {
        //修改
        this.modalTitle = "企业涉及安全标准裁剪修改"
        this.isUpdate = true;
        this.standards = [];
        this.changePlanJinyu(this.formData.auditPlanId);
        if (this.formData.auditType === '1') {
          this.standards = this.standards1
          this.formData.auditTypeName = '基础标准';
        } else if (this.formData.auditType === '2') {
          this.standards = this.standards2
          this.formData.auditTypeName = '现场标准';
        } else {
          this.standards = this.standards3
          this.formData.auditTypeName = '班组标准';
        }
        let _this = this;
        _this.orderTreeHead = [{
          id: 1,
          loading: true,
          title: '安全审计标准',
          expand: false,
          children: [],
        }]
        this.buttonLoading = true;
        this.model1 = true;
        this.$http.get(Api.checkerAuditTwoStandardsTreeList, {
          params: {standardsId: params.row.standardsId, id: params.row.id}
        }).then(function (res) {
          if (res.data.status == '200') {
            _this.orderTreeHead =
                [
                  {
                    id: 1,
                    loading: false,
                    title: '安全审计标准',
                    expand: true,
                    children: res.data.data
                  }
                ]
          }
          this.buttonLoading = false;
        }, function (res) {
          this.$Message.error('请求失败');
        });


      }
    },

    cancel() {
      this.formInline = {postId: "", name: ""};
      this.query();
    },
    changePlanJinyu(data) {

      let auditPlan = this.planDict[data];
      if (auditPlan.notes) {
        this.orgList = JSON.parse(auditPlan.notes);
      } else {
        this.orgList = [];
        this.$Message.warning('该审计计划下没有计划审计单位请添加！！！');
      }


    },
    addInfo() {
      let _this = this;
      this.modalTitle = "企业涉及安全标准裁剪新增"
      let year = _this.formatDate(new Date(), 'yyyy');
      let auditPlan;
      this.auditPlanList.forEach(item => {
        if (_this.formatDate(new Date(item.planStartTime), 'yyyy') == year) {
          auditPlan = item;
        }
      })


      this.formData = {
        auditTypeName: "",
        companyName: this.$route.query.companyName,
        auditName: this.$route.query.companyName,
        auditPlanId: auditPlan ? auditPlan.auditPlanId : null,
        companyId: this.$route.query.companyId,

      };

      this.orgList = [];
      if (auditPlan) {
        this.orgList = JSON.parse(auditPlan.notes);
      }
      this.model1 = true;
      this.isUpdate = false;
      this.isHead = true;
      this.orderTreeHead = [
        {
          id: 1,
          loading: false,
          title: '安全审计标准',
          expand: false,
          children: []
        }
      ]
    },
    pageSizeChange(pageSize) {
      this.pagedata.pageSize = pageSize;
      this.query();
    },
    pageChange(pageNum) {
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
        }
      }
      return fmt;
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length);
    },
    setOrgId(data) {
      this.$set(this.formData, 'companyId', data[data.length - 1])
    },
    setOrgName(data) {
      this.$set(this.formData, 'companyName', data)
      if (this.formData.companyName) {
        this.formData.auditName = this.formData.companyName + "_" + this.formData.auditTypeName
      }

    },
    saveInfo() {
      let _this = this;
      this.$refs['formCustom'].validate((valid) => {
        if (valid) {
          let tree = this.$refs.auditTree.getCheckedNodes();
          this.formData.list = tree;
          this.buttonLoading = true;
          if (_this.isUpdate) {
            let user = sessionStorage('userId').getObject('userId');
            _this.formData.updateUserid = user.userId;
            _this.formData.updateOrgId = user.orgInfo.orgId;
            _this.$http.put(Api.updateAuditTwoStandardsTreeList, _this.formData).then(function (response) {
              _this.buttonLoading = false;
              if (response.data.status == '200') {
                _this.model1 = false;
                _this.$Message.success({
                  content: '保存成功',
                  duration: 4
                });
                _this.query();
              } else {
                _this.$Message.warning({
                  content: response.data.msg,
                  duration: 4
                });
              }
            }).catch(e => {
              console.log(e)
              this.$Message.error("修改失败")
              this.buttonLoading = false;
            })
          } else {
            let user = sessionStorage('userId').getObject('userId');
            _this.formData.createUserId = user.userId;
            _this.formData.createOrgId = user.orgInfo.orgId;
            _this.$http.post(Api.saveAuditTwoTail, _this.formData).then(function (response) {
              _this.buttonLoading = false;
              if (response.data.status == '200') {
                _this.model1 = false;
                _this.$Message.success({
                  content: '保存成功',
                  duration: 4
                });
                _this.query();
              } else {
                _this.$Message.warning({
                  content: response.data.msg,
                  duration: 4
                });
              }

            }, function (response) {
              _this.$Message.error({
                content: '保存失败',
                duration: 4
              });
            }).catch(e => {
              console.log(e)
              this.$Message.error("新增失败")
              this.buttonLoading = false;
            });
          }

        }
      });
    },
  },
  watch: {}

}
</script>

<style scoped>


</style>
